<template>
  <view class="container">
    <!-- Hero Carousel Section -->
    <view class="hero-carousel">
      <!-- Carousel slides -->
      <swiper class="carousel-swiper" circular :autoplay="true" :interval="5000" :duration="500"
        @change="handleSwiperChange">
        <!-- Dynamic carousel items -->
        <swiper-item class="swiper-item" v-for="item in carouselItems" :key="item.id">
          <image class="slide-image" :src="item.imageUrl" mode="aspectFill" />
          <view class="slide-gradient" :class="item.gradientClass">
            <view class="slide-content">
              <!-- Show broadcasting text if available -->
              <view class="broadcasting" v-if="item.broadcasting">
                <text class="broadcast-icon">🔊</text>
                <text class="broadcast-text">正在播报</text>
              </view>
              <text class="slide-title">{{ item.title }}</text>
              <text class="slide-subtitle">{{ item.subtitle }}</text>
              <button class="slide-button" :class="item.buttonClass" @click="navigateToDaka(item.id, item.theme)">
                <text class="button-icon">{{ item.buttonIcon }}</text>
                <text>{{ item.buttonText }}</text>
              </button>
            </view>
          </view>
        </swiper-item>
      </swiper>

      <!-- Navigation arrows -->
      <!-- <view class="carousel-nav prev" @click="prevSlide">
        <text class="nav-arrow">〈</text>
      </view>
      <view class="carousel-nav next" @click="nextSlide">
        <text class="nav-arrow">〉</text>
      </view> -->

      <!-- Indicator dots -->
      <view class="carousel-indicators">
        <view v-for="(_, index) in carouselItems" :key="index" 
              :class="['indicator-dot', currentSlide === index ? 'active' : '']"
              @click="setSlide(index)">
        </view>
      </view>
    </view>

    <!-- Featured Themes Section -->
    <view class="featured-section">
      <view class="section-header">
        <text class="section-title">精选打卡主题</text>
        <view class="refresh-button" @click="refreshThemes" :disabled="isLoading">
          <text class="refresh-text">AI推荐主题</text>
          <text :class="['refresh-icon', isLoading ? 'refresh-rotating' : '']">🔄</text>
        </view>
      </view>
      <view class="card-grid">
        <view v-for="(theme, index) in featuredThemes" :key="index" class="theme-card" @click="selectTheme(theme)">
          <view class="card-image-container">
            <image :src="getThemeImageUrl(theme)" mode="aspectFill" class="card-image" />
            <view class="card-badge">
              <text>{{ getThemePoints(theme) }}分</text>
            </view>
          </view>
          <view class="card-content">
            <text class="card-title">{{ getThemeTitle(theme) }}</text>
            <text class="card-description">{{ getThemeDescription(theme) }}</text>
          </view>
          <view class="card-footer">
            <view class="visitors">
              <text class="visitor-icon">👥</text>
              <text class="visitor-count">{{ getThemeVisitorCount(theme) }}人打卡</text>
            </view>
            <text class="duration">约{{ getThemeDuration(theme) }}小时</text>
          </view>
        </view>
      </view>
    </view>

    <!-- Floating Action Button for My Themes -->
    <view class="floating-button" @click="navigateToMyThemes">
      <view class="fab-icon">
        <uni-icons type="person-filled" size="24" color="#fff"></uni-icons>
      </view>
      <text class="fab-text">我的打卡</text>
    </view>
  </view>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { defaultThemes, carouselItems } from './data.js'

export default {
  setup() {
    // State
    const featuredThemes = ref(defaultThemes);
    
    // Carousel state
    const currentSlide = ref(0);
    let swiperInstance = null;

    // Add loading state
    const isLoading = ref(false);

    const authStore = useAuthStore();
    
    // Initialize themes when component is mounted
    onMounted(() => {
      // initThemes();
    });
    
    // Fetch initial themes from API
    function initThemes() {
      isLoading.value = true;
      const userId = authStore.userInfo?.id || authStore.open_id || authStore.union_id || '123456';
      
      uni.request({
        url: 'https://tushuoit.com/api/ju/gis/map/show/topics',
        method: 'POST',
        data: '',
        header: {
          'accept': 'application/json'
        },
        params: {
          user_id: userId,
          recently_day: '100'
        },
        success: (res) => {
          if (res.data && res.data.code === 0 && res.data.data) {
            featuredThemes.value = res.data.data;
          } else {
            console.error('Failed to fetch themes:', res.data?.message || 'Unknown error');
            // Fallback to default themes if API fails
            featuredThemes.value = defaultThemes;
          }
        },
        fail: (err) => {
          console.error('Error fetching themes:', err);
          // Fallback to default themes if API fails
          featuredThemes.value = defaultThemes;
        },
        complete: () => {
          isLoading.value = false;
        }
      });
    }

    // Methods for carousel
    function handleSwiperChange(e) {
      currentSlide.value = e.detail.current;
    }

    function prevSlide() {
      if (swiperInstance) {
        const newIndex = (currentSlide.value - 1 + 3) % 3;
        swiperInstance.slideTo(newIndex);
        currentSlide.value = newIndex;
      }
    }

    function nextSlide() {
      if (swiperInstance) {
        const newIndex = (currentSlide.value + 1) % 3;
        swiperInstance.slideTo(newIndex);
        currentSlide.value = newIndex;
      }
    }

    function setSlide(index) {
      if (swiperInstance) {
        swiperInstance.slideTo(index);
        currentSlide.value = index;
      }
    }

    // Get swiper instance when it's ready
    function onReady() {
      const query = uni.createSelectorQuery();
      query.select('.carousel-swiper').node().exec((res) => {
        if (res[0] && res[0].node) {
          swiperInstance = res[0].node;
        }
      });
    }

    // Helper functions to extract data from the new theme format
    function getThemeTitle(theme) {
      return theme.topic || '';
    }

    function getThemeDescription(theme) {
      return theme.topic_desc || '';
    }

    function getThemePoints(theme) {
      return theme.sum_points || '0';
    }

    function getThemeDuration(theme) {
      return theme.spend_all_time || '0';
    }

    function getThemeImageUrl(theme) {
      // Try to get the first checkpoint's image if available
      if (theme.route_metadata && 
          theme.route_metadata.checkpoints && 
          theme.route_metadata.checkpoints.length > 0 &&
          theme.route_metadata.checkpoints[0].scenic_img_url) {
        return theme.route_metadata.checkpoints[0].scenic_img_url;
      }
      // Fallback to a default image
      return 'https://images.unsplash.com/photo-1470071459604-3b5ec3a7fe05?auto=format&fit=crop&q=80&w=300';
    }

    function getThemeVisitorCount(theme) {
      // Try to get the sum of all checkpoint visitor counts if available
      if (theme.route_metadata && 
          theme.route_metadata.checkpoints && 
          theme.route_metadata.checkpoints.length > 0) {
        let totalCount = 0;
        theme.route_metadata.checkpoints.forEach(checkpoint => {
          totalCount += parseInt(checkpoint.check_in_count || '0', 10);
        });
        return totalCount;
      }
      // Fallback
      return '0';
    }

    // Navigate to daka with theme
    function navigateToDaka(itemId, theme = '') {
      // Use the carousel item ID directly
      const themeId = `${itemId}`;
      
      if (!authStore.isLoggedIn) {
        handleLogin(() => {
          uni.navigateTo({
            url: `/pages/daka/daka?theme=${encodeURIComponent(theme)}&themeId=${themeId}`
          });
        });
        return;
      }
      uni.navigateTo({
        url: `/pages/daka/daka?theme=${encodeURIComponent(theme)}&themeId=${themeId}`
      });
    }

    function selectTheme(theme) {
      if (!authStore.isLoggedIn) {
        handleLogin(() => {
          uni.navigateTo({
            url: `/pages/daka/daka?theme=${encodeURIComponent(theme.topic)}&themeId=${theme.id || '1'}`
          });
        });
        return;
      }
      uni.navigateTo({
        url: `/pages/daka/daka?theme=${encodeURIComponent(theme.topic)}&themeId=${theme.id || '1'}`
      });
    }

    function handleLogin(successCallback) {
      uni.showLoading({
        title: '登录中...'
      });

      uni.login({
        provider: 'weixin',
        success: (loginRes) => {
          if (loginRes.code) {
            const accountInfo = uni.getAccountInfoSync();
            // 只发送code到后端换取token
            uni.request({
              url: 'https://tushuoit.com/api/ju/auth/login/wechat',
              method: 'POST',
              data: {
                code: loginRes.code,
                appId: accountInfo.miniProgram.appId
              },
              success: (res) => {
                if (res.data && res.data.access_token) {
                  // 使用 Pinia store 更新认证状态，传入完整的认证数据
                  authStore.setAuthData({
                    access_token: res.data.access_token,
                    token_type: res.data.token_type || 'bearer',
                    open_id: res.data.open_id || '',
                    union_id: res.data.union_id || ''
                  });

                  // 如果后端返回用户信息则保存，否则创建基本用户信息
                  if (res.data.userInfo) {
                    authStore.setUserInfo(res.data.userInfo);
                  } else {
                    // 创建基本用户信息，可能结合open_id
                    const basicUserInfo = {
                      avatarUrl: '/static/default-avatar.png',
                      nickName: '微信用户',
                      openId: res.data.open_id
                    };
                    authStore.setUserInfo(basicUserInfo);
                  }

                  uni.showToast({
                    title: '登录成功',
                    icon: 'success'
                  });
                  successCallback && successCallback();
                } else {
                  uni.showToast({
                    title: '登录失败，请重试',
                    icon: 'none'
                  });
                }
              },
              fail: (err) => {
                console.error('登录请求失败', err);
                uni.showToast({
                  title: '网络错误，请重试',
                  icon: 'none'
                });
              },
              complete: () => {
                uni.hideLoading();
              }
            });
          } else {
            uni.hideLoading();
            uni.showToast({
              title: '获取授权失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          uni.hideLoading();
          uni.showToast({
            title: '登录失败',
            icon: 'none'
          });
        }
      });
    }

    function refreshThemes() {
      isLoading.value = true;
      const userInfo = authStore.userInfo || {};
      // 使用 union_id 或 open_id 作为标识符
      const username = userInfo.nickName || '游客';
      const unionId = authStore.union_id || authStore.open_id || 'anonymous';
      
      // 更新为新的API端点
      const apiUrl = 'https://tushuoit.com/api/ju/gis/map/shuffle/topic';
      const today = new Date().toISOString().slice(0, 10).replace(/-/g, ''); // Format: 20250315
      const params = {
        username: username,
        union_id: unionId,
        today: today,
        prompt: encodeURIComponent('畅游山水'),
        max_topic_counts: 100,
        model: 'deepseek-r1-distill-qwen-32b',
        temperature: '0.3',
        use_stream: 'false',
        max_tokens: '2000'
      };
      
      // 拼接查询参数
      const queryString = Object.keys(params)
        .map(key => `${key}=${params[key]}`)
        .join('&');
      
      // 发起请求
      uni.request({
        url: `${apiUrl}?${queryString}`,
        method: 'POST',
        data: '', // 根据curl命令，提交一个空数据体
        header: {
          'accept': 'application/json'
        },
        success: (res) => {
          if (res.data && res.data.code === 0 && res.data.data) {
            // 更新主题数据
            featuredThemes.value = res.data.data;
            
            uni.showToast({
              title: '已更新推荐主题',
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: res.data.message || '刷新主题失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('刷新主题失败', err);
          uni.showToast({
            title: '网络错误，请重试',
            icon: 'none'
          });
        },
        complete: () => {
          isLoading.value = false;
        }
      });
    }

    // Navigate to My Themes
    function navigateToMyThemes() {
      if (!authStore.isLoggedIn) {
        handleLogin(() => {
          uni.navigateTo({
            url: '/pages/daka/my-themes'
          });
        });
        return;
      }
      uni.navigateTo({
        url: '/pages/daka/my-themes'
      });
    }

    return {
      featuredThemes,
      currentSlide,
      carouselItems,
      navigateToDaka,
      selectTheme,
      refreshThemes,
      handleSwiperChange,
      prevSlide,
      nextSlide,
      setSlide,
      onReady,
      isLoading,
      // Export the helper functions for use in template
      getThemeTitle,
      getThemeDescription,
      getThemePoints,
      getThemeDuration,
      getThemeImageUrl,
      getThemeVisitorCount,
      navigateToMyThemes
    };
  },
  onReady() {
    // Call onReady to get swiper instance
    this.onReady();
  }
};
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f8f0e3;
}

/* Hero Carousel */
.hero-carousel {
  position: relative;
  height: 200px;
  overflow: hidden;
  margin-bottom: 20px;
}

.carousel-swiper {
  width: 100%;
  height: 100%;
}

.swiper-item {
  position: relative;
  width: 100%;
  height: 100%;
}

.slide-image {
  width: 100%;
  height: 100%;
}

.slide-gradient {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to right, rgba(0, 0, 0, 0.7), transparent);
  display: flex;
  align-items: center;
}

.red-gradient {
  background: linear-gradient(to right, rgba(127, 29, 29, 0.7), transparent);
}

.nature-gradient {
  background: linear-gradient(to right, rgba(20, 83, 45, 0.7), transparent);
}

.slide-content {
  padding: 20px;
  width: 80%;
}

.broadcasting {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.broadcast-icon {
  font-size: 18px;
  margin-right: 8px;
  animation: pulse 2s infinite;
}

.broadcast-text {
  color: white;
  font-size: 14px;
  font-weight: bold;
}

@keyframes pulse {
  0% {
    opacity: 0.7;
  }

  50% {
    opacity: 1;
  }

  100% {
    opacity: 0.7;
  }
}

.slide-title {
  font-size: 24px;
  font-weight: bold;
  color: white;
  margin-bottom: 8px;
}

.slide-subtitle {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 20px;
}

.slide-button {
  display: flex;
  flex-direction: row;
  align-items: center;
  background-color: white;
  padding: 10px 16px;
  border-radius: 50px;
}

.red-button {
  background-color: #dc2626;
}

.nature-button {
  background-color: #16a34a;
}

.button-icon {
  margin-right: 8px;
  font-size: 16px;
}

.slide-button text {
  font-size: 14px;
  color: #000;
}

.red-button text {
  color: white;
}

.nature-button text {
  color: white;
}

/* Carousel Navigation */
.carousel-nav {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 40px;
  height: 40px;
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.hero-carousel:hover .carousel-nav {
  opacity: 1;
}

.carousel-nav.prev {
  left: 16px;
}

.carousel-nav.next {
  right: 16px;
}

.nav-arrow {
  color: white;
  font-size: 18px;
}

/* Carousel Indicators */
.carousel-indicators {
  position: absolute;
  bottom: 16px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 8px;
}

.indicator-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.5);
  transition: all 0.3s;
}

.indicator-dot.active {
  width: 24px;
  border-radius: 4px;
  background-color: white;
}

/* Featured Section */
.featured-section {
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.refresh-button {
  display: flex;
  align-items: center;
  background-color: transparent;
  padding: 5px;
  cursor: pointer;
}

.refresh-text {
  font-size: 12px;
  color: #8b6b4a;
  margin-right: 4px;
}

.refresh-icon {
  font-size: 14px;
  color: #8b6b4a;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.rotating {
  animation: rotating 0.5s linear;
}

.refresh-rotating {
  animation: rotating 1s linear infinite;
}

/* Card Grid */
.card-grid {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -5px;
}

.theme-card {
  width: calc(50% - 10px);
  margin: 5px;
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card-image-container {
  height: 80px;
  position: relative;
}

.card-image {
  width: 100%;
  height: 100%;
}

.card-icon {
  position: absolute;
  top: 10px;
  left: 10px;
  width: 24px;
  height: 24px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.card-content {
  padding: 12px;
}

.card-title {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.card-description {
  font-size: 12px;
  color: #666;
  line-height: 1.3;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-footer {
  padding: 0 12px 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.rating {
  display: flex;
}

.star {
  font-size: 12px;
  color: #ddd;
}

.star.active {
  color: #ffcc00;
}

.duration {
  font-size: 12px;
  color: #999;
}

/* Add styles for loading state and new card elements */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.loading-text {
  font-size: 14px;
  color: #8b6b4a;
}

.card-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
}

.visitors {
  display: flex;
  align-items: center;
}

.visitor-icon {
  font-size: 12px;
  margin-right: 4px;
}

.visitor-count {
  font-size: 12px;
  color: #666;
}

/* Adjust the card content to accommodate the new layout */
.card-content {
  padding: 12px;
  min-height: 48px;
}

/* Floating Action Button */
.floating-button {
  position: fixed;
  bottom: 80px;
  right: 20px;
  width: 60px;
  height: 60px;
  background-color: #8b6b4a;
  border-radius: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  z-index: 999;
}

.fab-icon {
  margin-bottom: 2px;
}

.fab-text {
  font-size: 10px;
  color: #fff;
}

/* Add animation for button press */
.floating-button:active {
  transform: scale(0.95);
}
</style>